package org.microframework.base.core.redis.config;

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleCacheErrorHandler;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.lang.Nullable;

import java.time.Duration;

/**
 * Redis配置类
 */
@EnableCaching
@AutoConfiguration(before = RedisAutoConfiguration.class)
@ConditionalOnClass(RedisOperations.class)
@ConditionalOnProperty(name = "spring.data.redis.enabled", havingValue = "true", matchIfMissing = true)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig implements CachingConfigurer {

	@Bean
	@ConditionalOnMissingBean(name = "redisTemplate")
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(connectionFactory);

		// 使用 GenericJackson2JsonRedisSerializer 来序列化和反序列化 redis 的 value 值
		// 此序列化器已经包含了类型信息，无需额外配置 ObjectMapper
		RedisSerializer<Object> serializer = new GenericJackson2JsonRedisSerializer();

		// 使用 StringRedisSerializer 来序列化和反序列化 redis 的 key 值
		template.setKeySerializer(new StringRedisSerializer());
		template.setValueSerializer(serializer);
		
		// Hash 的 key 也采用 StringRedisSerializer 的序列化方式
		template.setHashKeySerializer(new StringRedisSerializer());
		template.setHashValueSerializer(serializer);
		
		template.afterPropertiesSet();
		return template;
	}

	@Bean
	@Override
	@ConditionalOnMissingBean(name = "cacheManager")
	public CacheManager cacheManager() {
		// 创建Redis缓存管理器
		RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
				// 设置默认过期时间为1小时
				.entryTtl(Duration.ofHours(1))
				// 禁用缓存空值
				.disableCachingNullValues()
				// 设置key序列化器
				.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
				// 设置value序列化器
				.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));

		// 建立并返回缓存管理器
		return RedisCacheManager.builder(RedisConnectionFactory.class.cast(redisTemplate(null).getConnectionFactory()))
				.cacheDefaults(defaultCacheConfig)
				.transactionAware()
				.build();
	}

	@Bean
	@Override
	@Nullable
	public KeyGenerator keyGenerator() {
		return new SimpleKeyGenerator();
	}

	@Bean
	@Override
	@Nullable
	public CacheErrorHandler errorHandler() {
		return new SimpleCacheErrorHandler();
	}

	@Override
	@Nullable
	public CacheResolver cacheResolver() {
		return null;
	}
}